﻿Imports Lidgren.Network

Public Enum PacketTypes
    LOGIN
    WORLDSTATE
End Enum

Public Class NetworkingClient


    Public Client As Lidgren.Network.NetClient
    Public OutMsg As NetOutgoingMessage
    Public Enabled As Boolean = False

    Public Sub New(Optional ByVal HostIP As String = "192.168.1.4")
        Dim Config As New NetPeerConfiguration("DanoQuest") 'Must be same on server
        Client = New NetClient(Config)
        If Enabled Then
            Client.Start()
            Login(HostIP)
        End If
    End Sub

    Public Sub Login(ByVal HostIP As String)
        OutMsg = Client.CreateMessage()   'Dim LoginPacket as Lidgren.Network.N = new LoginPacket("Katu");
        OutMsg.Write(CByte(PacketTypes.LOGIN))
        OutMsg.Write("Player:Dano")
        Client.Connect(HostIP, 14444, OutMsg)
        WaitForStartingInfo()
    End Sub

    Public Sub WaitForStartingInfo()
        Dim Incoming As NetIncomingMessage
        While Not Enabled
            Incoming = Client.ReadMessage()
            If Incoming IsNot Nothing Then
                Select Case Incoming.MessageType
                    Case NetIncomingMessageType.Data ' All manually sent messages are type of "Data"
                        If Incoming.ReadByte() = CByte(PacketTypes.LOGIN) Then
                            Dim IsEnabled As Boolean = Incoming.ReadBoolean()
                            Debug.WriteLine("Client: Login " & IsEnabled)
                            Enabled = IsEnabled
                        End If
                        Exit Select
                    Case Else
                        Debug.WriteLine("Client: (Strange message) " & Incoming.ReadString())
                        Exit Select
                End Select
            End If
        End While
        SendMessage(PacketTypes.WORLDSTATE, "sup")
    End Sub

    Private Sub SendMessage(ByVal PacketType As PacketTypes, ByVal Data As Object)
        OutMsg = Client.CreateMessage()
        OutMsg.Write(CByte(PacketType))
        OutMsg.Write(Data) 'ToDo: Create Packet Structures
        Client.SendMessage(OutMsg, NetDeliveryMethod.ReliableOrdered)
    End Sub

End Class
